package guida.day03;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@WebServlet("/demo01")
public class Demo01 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String param1 = request.getParameter("name") == null ? "名字" : request.getParameter("name");
        String param2 = request.getParameter("url") == null ? "名字" : request.getParameter("url");
        // 为名字和姓氏创建 Cookie
        // 中文转码为%E6%B5%8B%E8%AF%95格式
        Cookie name = new Cookie("name", URLEncoder.encode(param1, "UTF-8"));
        Cookie url = new Cookie("url", param2);

        // 为两个 Cookie 设置过期日期为 24 小时后
        name.setMaxAge(60 * 60 * 24);
        url.setMaxAge(60 * 60 * 24);

        // 在响应头中添加两个 Cookie
        response.addCookie(name);
        response.addCookie(url);

        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String title = "设置 Cookie 实例";
        String docType = "<!DOCTYPE html>";
        out.println(docType + "<html><head><title>" + title + "</title></head>"
                + "<body bgcolor='#f0f0f0'>设置了两个cookie[name|url]</body></html>");
    }
}
